#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include<arpa/inet.h>
#include <error.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>

void* recvsocket(void* arg)//接受来着客户端数据的线程
{
    pthread_t thread_id = pthread_self();
    printf("--client recvsocket thread id: %lu\n", thread_id);

    int st = *(int*)arg;
    char s[1024];
    while (1)
    {
        memset(s, 0, sizeof(s));
        int rc = recv(st, s, sizeof(s), 0);
        if (rc <= 0)//代表socket被关闭（0）或者出错（-1）
        {
            printf("client recv fail:%d\n", rc);
            exit(-1); // 这里强制退出貌似不对，还有一个发送线程没有结束？？？
            break;
        }
        printf("client receive:%s\n", s);
    }
    return NULL;
}
void* sendsocket(void* arg)//向服务端socket发送数据的线程
{
    pthread_t thread_id = pthread_self();
    printf("--client sendsocket thread id: %lu\n", thread_id);
    int st = *(int*)arg;
    char s[1024];
    while (1)
    {
        memset(s, 0, sizeof(s));
        scanf("%s", s);
        int sc = send(st, s, strlen(s), 0);
    }
}
//执行 ./client.out 127.0.0.1 8080
//执行 ./client.out 192.168.64.4 8080
//执行 ./client.out 172.30.255.181 8080
int main(int arg, char* args[])
{
    if (arg < 3)
    {
        printf("arg<3\n");
        return - 1;
    }
    int port = atoi(args[2]);
    //第一步：初始化一个socket实例
    int st = socket(AF_INET, SOCK_STREAM, 0);

    //第二步：定义一个IP地址结构并设置值
    struct sockaddr_in addr;
    //内存初始化，将addr变量指向的内存签n个字节用0进行初始化填充
    memset(&addr, 0, sizeof(addr));
    //设置采用的协议为TCP/IP协议
    addr.sin_family = AF_INET;
    //设置端口号
    addr.sin_port = htons(port);
    //设置IP地址
    addr.sin_addr.s_addr = inet_addr(args[1]);

    //第三步：开始连接服务端
    if (connect(st, (struct sockaddr*) & addr, sizeof(addr)) == -1)
    {
        printf("connect fail %s\n", strerror(errno));
        return EXIT_FAILURE;
    }

    //第四步：初始化要发送的信息并且通过send函数发送数据
    pthread_t thrd1, thrd2;//定义一个线程
    pthread_create(&thrd1, NULL, recvsocket, &st);
    pthread_create(&thrd2, NULL, sendsocket, &st);
    pthread_join(thrd1,NULL);
    pthread_join(thrd2,NULL);

    close(st);
    // getchar();
    return EXIT_SUCCESS;
}